package com.godpaper.chessGameHall.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;
	import com.godpaper.chessGameHall.events.JoinRoomEvent;
	import com.godpaper.chessGameHall.events.RoomListUpdateEvent;
	import com.godpaper.chessGameHall.model.ConfigModelLocator;
	import com.godpaper.chessGameHall.model.RoomModelLocator;
	import com.godpaper.chessGameHall.view.components.RoomViewer;
	import com.godpaper.chessGameHall.util.StringUtil;
	
	import flash.display.DisplayObject;
	
	import it.gotoandplay.smartfoxserver.SFSEvent;
	import it.gotoandplay.smartfoxserver.data.Room;
	
	import mx.collections.Sort;
	import mx.collections.SortField;
	import mx.core.Application;
	import mx.managers.PopUpManager;
	import mx.rpc.IResponder;
	
	public class RoomListUpdateCommand extends CommandBase implements ICommand, IResponder
	{
		private var roomListUpdateEvent:RoomListUpdateEvent;
		private var roomModel:RoomModelLocator = RoomModelLocator.getInstance();
		private var configModel:ConfigModelLocator = ConfigModelLocator.getInstance();
		public function RoomListUpdateCommand()
		{
			super();
		}
		
		override public function execute(event:CairngormEvent):void
		{
			roomListUpdateEvent = RoomListUpdateEvent(event);
			roomListUpdateHandler(roomListUpdateEvent.sfsEvent);
		}
		
		private function roomListUpdateHandler(event:SFSEvent):void
		{
			PopUpManager.removePopUp( Application.application.iLoginViewer );
			Application.application.iLoginViewer = null;
			Application.application.iRoomViewer = 
				PopUpManager.createPopUp( Application.application as DisplayObject,RoomViewer,true);
			PopUpManager.centerPopUp( Application.application.iRoomViewer );
			
			trace("event.params.roomList:",event.params.roomList);
		 	
			// Populate the data provider with list of game rooms only
			var rList:Array = (event.params.roomList as Array);
			for each(var r:Room in rList)
			{
				if (r.isGame())
				{
					var txt:String = StringUtil.transactRoomLable( r );
					roomModel.roomList.addItem( {label:txt, data:r.getId()} );
				}
			}
		
			// Sort provider
			if (roomModel.roomList.sort == null)
			{
				var sort:Sort = new Sort();
				sort.fields = [new SortField("label")];
				
				roomModel.roomList.sort = sort;
			}
			roomModel.roomList.refresh();
			// Join the default room
			var joinRoomEvent:JoinRoomEvent = new JoinRoomEvent( configModel.sfsConfigVO.defaultRoom,
																 "" );
			CairngormEventDispatcher.getInstance().dispatchEvent( joinRoomEvent );											 
		}
		
		// Set room label in rooms list
		private function setRoomLabel(r:Room):String
		{
			var txt:String = r.getName() + " (" + r.getUserCount() + "/" + r.getMaxUsers() + ")"
			txt += "-(" + r.getSpectatorCount() + "/" + r.getMaxSpectators() + ")";
				
			return txt;
		}
	}
}